<template>
  <div class="app-container">
    <div class="contentBox">
      <div class="searchBox">
        <el-form :model="queryParams" ref="queryRef" :inline="true" @submit.prevent>
          <el-form-item prop="meterName" style="margin: 0 6px 0 0;">
            <el-input
                class="inputBox"
                v-model="queryParams.meterName"
                placeholder="请输入燃气表名称"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item style="margin: 0 6px 0 0;">
            <el-button class="normalFormBg searchBtn" icon="Search" @click="handleQuery"></el-button>
            <el-button class="normalFormBg searchBtn" icon="Refresh" @click="resetQuery"></el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-row :gutter="10" style="margin: 16px 0;">
        <el-col :span="1.5">
          <div class="normalBtn pageFlex pageFlexCenter" v-hasPermi="['gasManage:defaultSetting:gasMeterInfo:add']"
               @click="handleModalShow('新增燃气表信息')">
            <img src="@/assets/images/plus.png" class="normalBtn_icon">
            <div class="normalBtn_text">新增</div>
          </div>
        </el-col>
      </el-row>
      <el-table
        v-loading="loading"
        :data="dataList"
        border>
        <el-table-column prop="meterNo" label="编号" width="150" :show-overflow-tooltip="true" fixed="left"></el-table-column>
        <el-table-column prop="meterName" label="名称" width="150" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="meterPicture" label="图片" width="80" align="center">
          <template #default="scope">
            <div class="tableImgBox1">
              <el-image class="img" fit="contain" lazy :src="setCoverUrl(scope.row.meterPicture)"
                @click="handlePreviewShow(setCoverUrl(scope.row.meterPicture))" v-if="scope.row.meterPicture" />
              <div class="emptyBox" v-else>暂无图标</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="manufacturerId" label="生产商ID" width="150" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="meterType" label="类型" width="150" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="caliber" label="口径" width="150" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="maxRange" label="最大量程" width="150" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="overCurrentProtectionValue" label="过电流保护值" width="150" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="useYears" label="使用年限" width="150" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="protocol" label="使用协议" width="200" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="操作" width="340" align="center" fixed="right">
          <template #default="scope">
            <div class="pageFlex pageFlexCenter" style="width: 100%;">
              <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:defaultSetting:gasMeterInfo:list']"
                @click="handleInfo(scope.row.id)">
                <img src="@/assets/images/fileManage.png" class="img">
                <div class="text">详情</div>
              </div>
              <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:defaultSetting:gasMeterInfo:edit']"
                @click="handleEdit(scope.row.id)">
                <img src="@/assets/images/edit.png" class="img">
                <div class="text">修改</div>
              </div>
              <div class="pageFlex pageFlexCenter btnSetBox" v-hasPermi="['gasManage:defaultSetting:gasMeterInfo:delete']"
                @click="handleDelete(scope.row)">
                <img src="@/assets/images/delete.png" class="img">
                <div class="text">删除</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <template #empty>
          <el-empty description="暂无数据" />
        </template>
      </el-table>
      <div class="pageFlex pageAlignCenter pageSpaceBetween" style="margin-top: 20px;">
        <div class="totalText">共计 {{total}} 条</div>
        <el-pagination background layout="prev, pager, next" :total="total" :current-page="queryParams.pageNum" :page-size="queryParams.pageSize" @current-change="handleCurrentChange"/>
      </div>
    </div>
    <el-image-viewer :url-list="srcList" @close="handlePreviewClose" v-if="showPreview"/>
    <el-drawer v-model="modalShow" direction="rtl" size="600" :title="modalTitle">
      <div class="modalBox">
        <div class="modalBoxContent">
          <el-form
            ref="formRef"
            class="formContent"
            label-width="110"
            :model="form"
            :rules="rules"
            :disabled="modalTitle === '燃气表信息详情'"
          >
            <div class="formContentTop pageFlex pageAlignCenter">
              <div class="line"></div>
              <div class="title">燃气表信息</div>
            </div>
            <div class="formContentCenter bgFF">
              <el-form-item label="燃气表图片" prop="meterPicture">
                <div class="imgBox">
                  <ImageUpload ref="cover" v-model="form.meterPicture" bg="#FFFFFF" v-if="modalShow"></ImageUpload>
                </div>
              </el-form-item>
              <el-form-item label="燃气表名称" prop="meterName">
                <el-input
                  class="inputBox"
                  v-model="form.meterName"
                  placeholder="请输入燃气表名称"
                  clearable
                />
              </el-form-item>
              <el-form-item label="燃气表生产商" prop="manufacturerName">
                <div class="valueBox pageFlex pageAlignCenter" :class="{'disable': modalTitle === '燃气表信息详情'}" @click="showTableModal('manufacturerId')">
                  <el-text class="value">{{ form.manufacturerName || '请选择燃气表生产商' }}</el-text>
                  <el-icon><ArrowRight /></el-icon>
                </div>
              </el-form-item>
              <el-form-item label="燃气表类型" prop="meterType">
                <el-select class="inputBox" v-model="form.meterType" placeholder="请选择燃气表类型" clearable>
                  <el-option v-for="dict in gas_meter_type" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="燃气表地址"></el-form-item>
              <el-form-item label="燃气卡"></el-form-item>
              <el-form-item label="燃气表计量数量"></el-form-item>
              <el-form-item label="账户余额"></el-form-item>
              <el-form-item label="燃气表倍率"></el-form-item>
              <el-form-item label="燃气表底数"></el-form-item>
              <el-form-item label="修正值/校正值"></el-form-item>
              <el-form-item label="采集器"></el-form-item>
              <el-form-item label="集中器"></el-form-item>
              <el-form-item label="最大量程" prop="maxRange">
                <el-input
                  type="number"
                  class="inputBox"
                  v-model="form.maxRange"
                  placeholder="请输入最大量程"
                  clearable
                />
              </el-form-item>
              <el-form-item label="过电流保护值" prop="overCurrentProtectionValue">
                <el-input
                    type="number"
                    class="inputBox"
                    v-model="form.overCurrentProtectionValue"
                    placeholder="请输入过电流保护值"
                    clearable
                />
              </el-form-item>
              <el-form-item label="口径" prop="caliber">
                <el-input
                    class="inputBox"
                    v-model="form.caliber"
                    placeholder="请输入燃气表口径"
                    clearable
                />
              </el-form-item>
              <el-form-item label="使用年限" prop="useYears">
                <el-select v-model="form.useYears" placeholder="请选择年限" style="width: 360px">
                  <el-option
                      v-for="item in 20"
                      :key="item"
                      :label="item+'年'"
                      :value="item"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="燃气表状态"></el-form-item>
              <el-form-item label="使用协议" prop="protocol">
                <el-input
                    type="textarea"
                    class="textareaBox"
                    v-model="form.protocol"
                    :rows="6"
                    placeholder="请输入使用协议"
                    clearable
                />
              </el-form-item>
              <el-form-item label="描述" prop="description">
                <el-input
                    type="textarea"
                    class="textareaBox"
                    v-model="form.description"
                    :rows="6"
                    placeholder="请输入描述"
                    clearable
                />
              </el-form-item>
              <el-form-item label="备注"></el-form-item>
            </div>
          </el-form>
        </div>
        <div class="lineBox" v-if="modalTitle !== '燃气表信息详情'"></div>
        <div class="bottomBox pageFlex pageFlexCenter" v-if="modalTitle !== '燃气表信息详情'">
          <el-button type="primary" :loading="submitLoading" @click="submitNow">确认提交</el-button>
        </div>
        <el-button type="primary" :loading="formLoading" class="modalLoadingBox" v-if="formLoading">加载数据中</el-button>
      </div>
    </el-drawer>
    <el-dialog v-model="manufacturerShow" title="选择供货商" width="825">
      <div class="tableModalBox" v-if="manufacturerShow">
        <div class="tableModalBox_top pageFlex pageAlignCenter">
          <div class="line"></div>
          <div class="title">请进行选择</div>
        </div>
        <div class="searchBox">
          <el-form :model="manufacturerParams" ref="manufacturerTableModal" :inline="true" @submit.prevent>
            <el-form-item prop="name" style="margin: 0 6px 0 0;">
              <el-input
                  class="inputBox"
                  v-model="manufacturerParams.name"
                  placeholder="请输入供货商名称"
                  clearable
                  @keyup.enter="handleTableModalQuery()"
              />
            </el-form-item>
            <el-form-item style="margin: 0 6px 0 0;">
              <el-button class="normalFormBg searchBtn" icon="Search" @click="handleTableModalQuery()"></el-button>
              <el-button class="normalFormBg searchBtn" icon="Refresh" @click="resetTableModalQuery()"></el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="tableBox">
          <el-table
            ref="manufacturerTableRef"
            v-loading="manufacturerLoading"
            :data="manufacturerDataList"
            border
            height="400"
            @select="handleTableModalSelect"
            @select-all="handleTableModalAll">
            <el-table-column type="selection" width="55" :selectable="setTableModalSelectable"/>
            <el-table-column prop="id" label="企业ID" width="150" :show-overflow-tooltip="true" fixed="left"></el-table-column>
            <el-table-column prop="companyName" label="企业名称" width="200" :show-overflow-tooltip="true" fixed="left"></el-table-column>
            <el-table-column prop="thumb" label="LOGO" width="80" align="center">
              <template #default="scope">
                <div class="tableImgBox2">
                  <el-image class="img" fit="contain" lazy :src="setCoverUrl(scope.row.thumb)" v-if="scope.row.thumb" />
                  <div class="emptyBox" v-else>暂无图片</div>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="contacts" label="联系人" width="200" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="telephone" label="联系电话" width="150" :show-overflow-tooltip="true"></el-table-column>
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
          </el-table>
          <div class="pageFlex pageAlignCenter pageSpaceBetween" style="margin-top: 20px;">
            <div class="totalText">共计 {{manufacturerTotal}} 条</div>
            <el-pagination background layout="prev, pager, next" :total="manufacturerTotal" :current-page="manufacturerParams.pageNum" :page-size="manufacturerParams.pageSize" @current-change="handleTablePageChange"/>
          </div>
        </div>
        <div class="lineBox"></div>
        <div class="bottomBox pageFlex pageFlexCenter">
          <el-button @click="clearTableModalChoose">清空当前选择</el-button>
          <el-button type="primary" :disabled="!manufacturerCur" @click="confirmTableModalChoose">确认选择</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script setup>
import {computed, onMounted, nextTick} from 'vue';
import ImageUpload from '@/views/gasManage/components/ImageUpload';
import { searchGasMeterInfoApi, searchGasMeterInfoByIdApi, deleteGasMeterInfoApi, editGasMeterInfoApi, addGasMeterInfoApi } from '@/api/gasManage/defaultSetting/gasMeterInfo';
import { searchManufacturerApi } from '@/api/gasManage/defaultSetting/companyInfo';
import {ElLoading, ElMessageBox} from 'element-plus';
const { proxy } = getCurrentInstance();
const { gas_meter_type } = proxy.useDict("gas_meter_type");
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  meterName: ''
})
const loading = ref(false);
const total = ref(0);
const dataList = ref([]);
function handleQuery(){
  queryParams.value.pageNum = 1;
  getList();
}
function resetQuery(){
  proxy.resetForm("queryRef");
  handleQuery();
}
async function getList(){
  loading.value = true;
  let data = await getUserInfoList(queryParams.value);
  if(data && Array.isArray(data)){
    dataList.value = data;
  }else{
    dataList.value = [];
  }
  loading.value = false;
}
function getUserInfoList(params){
  return new Promise(resolve => {
    searchGasMeterInfoApi(params).then(res => {
      total.value = Number(res.total);
      resolve(Array.isArray(res.rows) ? res.rows : []);
    }).catch(() => {resolve(false)})
  })
}
function handleCurrentChange(e){
  queryParams.value.pageNum = e;
  getList();
}
// ----------------------------查看图片---------------------------
const showPreview = ref(false);
const srcList = ref([])
function handlePreviewShow(link){
  srcList.value = [link];
  showPreview.value = true;
}
function handlePreviewClose(){
  showPreview.value = false;
  srcList.value = [];
}
// ----------------------------弹窗-------------------------------
const modalShow = ref(false);
const modalTitle = ref('');
const formLoading = ref(false);
const submitLoading = ref(false);
const form = ref({
  meterPicture: '',
  meterName: '',
  manufacturerId: '',
  manufacturerName: '',
  meterType: '',
  maxRange: '',
  overCurrentProtectionValue: '',
  caliber: '',
  protocol: '',
  description: '',
  useYears: ''
})
const rules = ref({
  meterPicture: [{ required: true, message: "燃气表图片未上传", trigger: "blur" }],
  meterName: [{ required: true, message: "燃气表名称不能为空", trigger: "blur" }],
  manufacturerName: [{ required: true, message: "燃气表生产商不能为空", trigger: "blur" }],
  meterType: [{ required: true, message: "燃气表类型不能为空", trigger: "blur" }],
  maxRange: [{ required: true, message: "最大量程不能为空", trigger: "blur" }],
  overCurrentProtectionValue: [{ required: true, message: "过电流保护值不能为空", trigger: "blur" }],
  caliber: [{ required: true, message: "口径不能为空", trigger: "blur" }],
  useYears: [{ required: true, message: "使用年限不能为空", trigger: "blur" }],
  protocol: [{ required: true, message: "使用协议不能为空", trigger: "blur" }],
});
function handleModalShow(name){
  proxy.resetForm('formRef');
  form.value.manufacturerId = '';
  modalTitle.value = name;
  modalShow.value = true;
}
function handleModalHide(){
  modalShow.value = false;
}
function submitNow(){
  if(submitLoading.value) return;
  proxy.$refs["formRef"].validate(valid => {
    if(valid){
      submitLoading.value = true;
      if(modalTitle.value === '新增燃气表信息'){
        addNow();
      }else{
        editNow();
      }
    }else{
      proxy.$modal.alertWarning('信息填写有误，请检查！');
    }
  })
}
function setFormData(id){
  formLoading.value = true;
  searchGasMeterInfoByIdApi(id).then(res=>{
    let data = JSON.parse(JSON.stringify(res.data));
    data.manufacturerId = String(data.manufacturerId);
    data.meterType = String(data.meterType);
    form.value = data;
    formLoading.value = false;
  }).catch(err=>{
    formLoading.value = false;
    handleModalHide();
  })
}
// ----------------------------详情-------------------------------
function handleInfo(id){
  handleModalShow('燃气表信息详情');
  setFormData(id);
}
// ----------------------------修改-------------------------------
function handleEdit(id){
  handleModalShow('修改燃气表信息');
  setFormData(id);
}
function editNow(){
  let params = JSON.parse(JSON.stringify(form.value));
  editGasMeterInfoApi(params).then(() => {
    submitLoading.value = false;
    handleModalHide();
    proxy.$modal.msgSuccess('修改燃气表信息成功');
    getList();
  }).catch(()=>{
    submitLoading.value = false;
  })
}
// ----------------------------新增-------------------------------
function addNow(){
  addGasMeterInfoApi(form.value).then(() => {
    submitLoading.value = false;
    handleModalHide();
    proxy.$modal.msgSuccess('新增燃气表信息成功');
    getList();
  }).catch(()=>{
    submitLoading.value = false;
  })
}
//----------------------删除--------------------------
function handleDelete(row){
  ElMessageBox.confirm(`确认删除燃气表名称为【${row.name}】的数据`,'提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteNow(row);
  }).catch(() => {})
}
async function deleteNow(row){
  const loading = ElLoading.service({
    lock: true,
    text: '删除中~',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  deleteGasMeterInfoApi(row.id).then(()=>{
    loading.close();
    proxy.$modal.msgSuccess(row.name+'燃气表删除成功');
    getList();
  }).catch(()=>{
    loading.close();
  })
}
// --------------------------------------表格弹窗统一处理----------------------------
const baseUrl = import.meta.env.VITE_APP_BASE_API;
const setCoverUrl = computed(()=>{
  return url => {
    if(url){
      return baseUrl+url
    }
    return  ''
  }
})
function showTableModal(name){
  if(modalTitle.value === '燃气表信息详情') return;
  manufacturerShow.value = false;
  manufacturerCur.value = null;
  if(name === 'manufacturerId'){
    manufacturerShow.value = true;
    handleTableModalQuery();
    nextTick(()=>{
      proxy.$refs.manufacturerTableRef.clearSelection();
    })
  }
}
function handleTableModalQuery(){
  if(manufacturerShow.value){
    manufacturerParams.value.pageNum = 1;
  }
  handleGetTableList();
}
function handleGetTableList(){
  if(manufacturerShow.value){
    manufacturerLoading.value = true;
    searchManufacturerApi(manufacturerParams.value).then(res=>{
      manufacturerTotal.value = Number(res.total);
      manufacturerDataList.value = Array.isArray(res.rows) ? res.rows : [];
      manufacturerLoading.value = false;
      if(form.value.manufacturerId && manufacturerDataList.value.length){
        let index = manufacturerDataList.value.findIndex(item=>item.id === form.value.manufacturerId);
        if(index !== -1){
          nextTick(()=>{
            manufacturerCur.value = manufacturerDataList.value[index];
            proxy.$refs.manufacturerTableRef.toggleRowSelection(manufacturerCur.value, true);
          })
        }
      }
    }).catch(()=>{
      manufacturerLoading.value = false;
      manufacturerDataList.value = [];
    })
  }
}
function setTableModalSelectable(row){
  return row.validated == 3
}
function resetTableModalQuery(){
  if(manufacturerShow.value){
    proxy.resetForm("manufacturerTableModal");
    handleTableModalQuery();
  }
}
function handleTableModalSelect(e){
  let data = e[0];
  if(manufacturerShow.value){
    if(e.length > 1){
      data = e[1]
    }
    if(!data || (manufacturerCur.value && manufacturerCur.value.id && manufacturerCur.value.id === data.id)){
      manufacturerCur.value = null;
      return false;
    }
    let index = manufacturerDataList.value.findIndex(item=>item.id === data.id);
    proxy.$refs.manufacturerTableRef.clearSelection();
    manufacturerCur.value = data;
    proxy.$refs.manufacturerTableRef.toggleRowSelection(manufacturerDataList.value[index], true);
  }
}
function handleTableModalAll(){
  if(manufacturerShow.value){
    proxy.$refs.manufacturerTableRef.clearSelection();
    manufacturerCur.value = null;
  }
}
function handleTablePageChange(e){
  if(manufacturerShow.value){
    manufacturerParams.value.pageNum = e;
    handleGetTableList();
  }
}
function clearTableModalChoose(){
  if(manufacturerShow.value){
    form.value.manufacturerId = '';
    form.value.manufacturerName = '';
    proxy.$refs.manufacturerTableRef.clearSelection();
    hideTableModal();
  }
}
function confirmTableModalChoose(){
  if(manufacturerShow.value){
    form.value.manufacturerId = manufacturerCur.value.id;
    form.value.manufacturerName = manufacturerCur.value.companyName;
    hideTableModal();
  }
}
function hideTableModal(){
  if(manufacturerShow.value){
    manufacturerShow.value = false;
  }
}
// ------------------------------------燃气表生产商选择-------------------------------
const manufacturerShow = ref(false);
const manufacturerLoading = ref(false);
const manufacturerDataList = ref([]);
const manufacturerTotal = ref(0);
const manufacturerCur = ref(null);
const manufacturerParams = ref({
  pageNum: 1,
  pageSize: 10,
  name: ''
});
onMounted(()=>{
  getList();
})
</script>
<style lang='scss' scoped>
@import "@/assets/styles/public.scss";
:deep(.el-input){
  .el-input__wrapper{
    background-color: $formBgSet;
    box-shadow: none;
  }
}
.app-container{
  width: 100%;
  min-height: calc(100vh - 66px);
  background: #F8F8F9;
  .contentBox{
    width: 100%;
    min-height: $pageMinHeight;
    background-color: #FFFFFF;
    border-radius: 5px;
    box-sizing: border-box;
    padding: 12px;
    .searchBtn{
      width: 32px;
      height: 32px;
      font-size: 12px;
      padding: 0;
      border: none;
      margin: 0 6px 0 0px;
    }
    .btnSetBox{
      padding: 0 10px;
      box-sizing: border-box;
      border-right: 1px solid $borderColor;
      cursor: pointer;
      .text{
        height: 16px;
        line-height: 16px;
        color: var(--el-color-primary);
      }
      .img{
        width: 16px;
        height: 16px;
        margin-right: 2px;
      }
      &:last-child{
        border-right: none;
      }
    }
    .totalText{
      height: 22px;
      font-weight: 400;
      font-size: 14px;
      color: #1D2129;
      line-height: 22px;
    }
  }
}
:deep(.el-drawer){
  .el-drawer__header{
    margin: 0;
    padding-bottom: 20px;
  }
  .el-drawer__body{
    padding: 0;
  }
}
</style>

